package com.heima.controller.web.region;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.controller.Result;
import com.heima.pojo.Node;
import com.heima.pojo.Region;
import com.heima.pojo.vo.Dto.RegionDto;
import com.heima.service.NodeService;
import com.heima.service.RegionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/api/vm-service/region")
public class RegionController {

    @Autowired
    private RegionService regionService;

    @Autowired
    private NodeService nodeService;

    /**
     * 分页查询
     * 查询count的个数
     *
     * @return
     */
    @GetMapping("/search")
    public Result<List<RegionDto>> findByPage(Integer pageIndex, Integer pageSize, String className) throws JsonProcessingException {
        //健壮性
        log.info("区域管理，第{}页，每页{}条", pageIndex, pageSize);
        //健壮性
        if (pageSize == null) {
            pageSize = 10;
        }
        if (pageIndex == null) {
            pageIndex = 1;
        }
        //根基id 查询个数 并且进行分页 查询
        //创建分页对象
        Page<Region> page = new Page<>(pageIndex, pageSize);
        //创建分页条件
        LambdaQueryWrapper<Region> qw = new LambdaQueryWrapper<>();
        //模糊查询
        qw.like(className != null, Region::getName, className);
        //进行分页查询
        regionService.page(page, qw);
        //新建一个新的查询对象
        Page<RegionDto> regionVoPage = new Page<>();
        //进行复制
        BeanUtils.copyProperties(page, regionVoPage, "records");
        //获取原来的数据
        List<Region> records = page.getRecords();
        //用流 进行填充
        List<RegionDto> collect = records.stream().map((record) -> {
            Long id1 = record.getId();
            log.info("id的数据是{}", id1);
            //属性复制
            RegionDto regionVo = new RegionDto();
            BeanUtils.copyProperties(record, regionVo);
            Long id = record.getId();
            //查询个数  然后进行赋值        //根据 region_id 进行查询
            LambdaQueryWrapper<Node> qw2 = new LambdaQueryWrapper<>();
            qw2.eq(id != null, Node::getRegionId, id);
            int count = nodeService.count(qw2);
            log.info("count的数据是{}", count);
            regionVo.setNodeCount(count);
            return regionVo;
        }).collect(Collectors.toList());
        Result<List<RegionDto>> success = Result.success(pageIndex, pageSize, regionVoPage.getPages(), regionVoPage.getTotal(), collect);
        System.out.println("new ObjectMapper().writeValueAsString(success) = " + new ObjectMapper().writeValueAsString(success));
        return success;
    }

    /**
     * 新增区域
     *
     * @return
     */
    @PostMapping
    public boolean addRegion(@RequestBody Map<String, String> map) {
//        @RequestBody Map<String,String> map
//        @RequestBody Map<String,String> map
        log.info("进行添加 收到的数据是={}", map);
        String regionName = map.get("regionName");
        String remark = map.get("remark");
//        健壮性
//        判断名称
        log.info("进行添加 收到的数据是={},{}", regionName, remark);
        LambdaQueryWrapper<Region> qw = new LambdaQueryWrapper<>();
        qw.eq(StringUtils.isNotBlank(remark), Region::getName, remark);
        Region one = regionService.getOne(qw);
        //不存在
        if (one == null) {
            Region region = new Region();
            region.setName(regionName);
            region.setRemark(remark);
            boolean flag = regionService.save(region);
            if (flag) {
                return true;
            }
            return false;
        }
        return false;


    }

    /**
     * 修改区域
     */
    @PutMapping("/{id}")
    public boolean updateRegion(@RequestBody Map<String, String> map, @PathVariable Long id) {
        log.info("ID是={}", id);
        String regionName = map.get("regionName");
        String remark = map.get("remark");
        //根据id进行修改
        Region region = new Region();
        region.setRemark(remark);
        region.setName(regionName);
        region.setId(id);
        //健壮性
        LambdaQueryWrapper<Region> qw = new LambdaQueryWrapper<>();
        qw.eq(StringUtils.isNotBlank(remark), Region::getName, remark);
        Region one = regionService.getOne(qw);
        //不存在
        if (one == null) {
            boolean flag = regionService.updateById(region);
            if (flag) {
                return true;
            }
            return false;
        }
        return false;
    }

    /**
     * 删除区域
     * 如果区域下存在点位则不能进行删除
     */

    @DeleteMapping("/{id}")
    public boolean delayRegionIfNotNode(@PathVariable Long id) {

        boolean flag = regionService.delayRegionIfNotNode(id);
        if (flag){
            return true;
        }
        return false;
    }


}